package com.cloud.service.assets.impl;

import com.cloud.dao.assets.AssetsDao;
import com.cloud.dao.assetsdetail.AssetsDetailDao;
import com.cloud.model.entity.assets.Assets;
import com.cloud.model.entity.assetsdetail.AssetsDetail;
import com.cloud.model.view.assets.AssetsView;
import com.cloud.model.view.assetsdetail.AssetsDetailView;
import com.cloud.service.assets.AssetsService;
import com.cloud.commons.utils.CloudCopyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
* <b><code>AssetsImpl</code></b>
* <p/>
* Assets的具体实现
* <p/>
* <b>Creation Time:</b> 2019-10-15 17:21:44.
*
* @author ${model.author}
* @version 1.0.0
* @since cloud-spring-boot-be 1.0.0
*/
@Service
public class AssetsServiceImpl implements AssetsService {

    /**
     * The Constant LOG.
     */
    private static final Logger LOG = LoggerFactory
            .getLogger(AssetsServiceImpl.class);

    @Autowired
    private AssetsDao assetsDao;

    @Autowired
    private AssetsDetailDao assetsDetailDao;

    @Override
    public AssetsView getEntity(long id) {
        // 获取Entity
        Assets assets = assetsDao.findById(id).orElseThrow(() -> new RuntimeException("获取不到id为：" + id + "的数据记录"));
        // 复制Dao层属性到view属性
        AssetsView assetsView = new AssetsView();
        CloudCopyUtils.copyBean(assets, assetsView);
        return assetsView;
    }

    @Override
    public long getEntitiesCount() {
        return assetsDao.count();
    }

    @Override
    public List<AssetsView> findAll() {
        List<AssetsView> assetsViews = new ArrayList<>();
        List<Assets> assetss = assetsDao.findAll();
        for (Assets assets : assetss){
            AssetsView assetsView = new AssetsView();
            CloudCopyUtils.copyBean(assets, assetsView);
            assetsViews.add(assetsView);
        }
        return assetsViews;
    }

    @Override
    public AssetsView saveEntity(AssetsView assetsView)  {
        // 保存的业务逻辑
        Assets assets = new Assets();
        CloudCopyUtils.copyBean(assetsView, assets);
        // user数据库映射传给dao进行存储
        assets.setCreateTime(System.currentTimeMillis());
        assets.setUpdateTime(System.currentTimeMillis());
        assets.setWeight(System.currentTimeMillis());
        assets.setEnabled(1);
        assetsDao.save(assets);
        CloudCopyUtils.copyBean(assets,assetsView);
        return assetsView;
    }

    @Override
    public void deleteEntity(long id) {
        Assets assets = assetsDao.findById(id).orElseThrow(() -> new RuntimeException("获取不到id为：" + id + "的数据记录"));
        assets.setId(id);
        assetsDao.delete(assets);
    }

    @Override
    @Transactional(rollbackOn = { Exception.class })
    public void deleteEntities(String ids) {
        String[] entityIds= ids.split("\\,");
        List<Assets> assetss = new ArrayList<>();
        for(String entityId : entityIds){
            Assets assets = new Assets();
            assets.setId(Long.valueOf(entityId));
            assetss.add(assets);
        }
        assetsDao.deleteInBatch(assetss);
    }

    @Override
    public void updateEntity(AssetsView assetsView) {
        Specification<Assets> assetsSpecification = Optional.ofNullable(assetsView).map( s -> {
            return new Specification<Assets>() {
                @Override
                public Predicate toPredicate(Root<Assets> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    List<Predicate> predicates = new ArrayList<>();
                    // id
                    predicates.add(criteriaBuilder.equal(root.get("id").as(Long.class), s.getId()));

                    criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
                    return criteriaQuery.getRestriction();
                }
            };
        }).orElseThrow(()->new IllegalArgumentException("AssetsView is null"));


        // 获取原有的属性，把不变的属性覆盖
        Optional<Assets> assetsOptionalBySearch = assetsDao.findOne(assetsSpecification);
        assetsOptionalBySearch.map(assetsBySearch -> {
            CloudCopyUtils.copyBeanExcludeNull(assetsView,assetsBySearch);
            assetsBySearch.setUpdateTime(System.currentTimeMillis());
            assetsDao.save(assetsBySearch);
            return "";
        }).orElseThrow(()->new RuntimeException("无法找到id为" + assetsView.getId() + "的数据记录"));
    }

    @Override
    public AssetsView getAssetsViewByUserId(Long userId) {
        Assets assets = assetsDao.findByUserId(userId);
        if (ObjectUtils.isEmpty(assets)) {
            throw new RuntimeException("获取不到用户id:" + userId + "的统计数据，请重新登录");
        }
        AssetsView assetsView = new AssetsView();
        CloudCopyUtils.copyBean(assets,assetsView);
        // 获取每月详情信息
        List<AssetsDetail> assetsDetails = assetsDetailDao.findByAssetsId(assets.getId());
        if (ObjectUtils.isEmpty(assetsDetails) || assetsDetails.size() == 0) {
            return assetsView;
        }
        List<AssetsDetailView> assetsDetailViews = new ArrayList<>();
        for (AssetsDetail assetsDetail:assetsDetails) {
            AssetsDetailView assetsDetailView = new AssetsDetailView();
            CloudCopyUtils.copyBean(assetsDetail,assetsDetailView);
            assetsDetailViews.add(assetsDetailView);
        }
        assetsView.setAssetsDetailViews(assetsDetailViews);
        return assetsView;
    }
}
